using System;
using System.Collections.Generic;
using System.Text;
using FSoft.OVM.Common;
using FSoft.OVM.Common.BusinessObjects;
using System.Net.Mail;
using System.Diagnostics;
using System.Configuration;
using System.Net.Mime;
using System.IO;

namespace FSoft.OVM.Common.WindowService
{
    public class EmailService
    {
        private string defaultEmailAddress = ConfigurationManager.AppSettings.Get("EMAIL_TRANSMISSION_FROM_EMAIL");
        private string defaultEmailName = ConfigurationManager.AppSettings.Get("EMAIL_TRANSMISSION_FROM_NAME");

        private string logName = "Application";
        private EventLog log;

        public EmailService()
        {
            this.log = new EventLog();
            this.log.Source = this.logName;
            //VietNm TimeZone
            //Init TimeZone 11/04/2010
            try
            {
                FSoft.OVM.Common.BusinessObjects.SystemTimeZone.connectstring = ConfigurationManager.ConnectionStrings["OVM"].ConnectionString;
                FSoft.OVM.Common.BusinessObjects.SystemTimeZone.isService = true;
                FSoft.OVM.Common.BusinessObjects.SystemTimeZone.GetVarianceTimeZone();
            }
            catch
            {
                Utils.WriteLog(Utils.ObjectJobLog.ServiceManager, "Can not get variance timezone in service!");
            }

        }

        public void SendPendingTransmission()
        {
            EmailTransmissionInfoList emailList = EmailTransmissionInfoList.GetPendingEmailTransmissionInfoList();

            SmtpClient smtpSend = new SmtpClient();

            foreach (EmailTransmissionInfo emailInfo in emailList)
            {
                MailMessage mailMessage = new MailMessage();

                EmailTransmissionBO emailBO = EmailTransmissionBO.GetEmailTransmissionBO(emailInfo.EmailTransmissionID);

                try
                {

                    mailMessage.From = new MailAddress(defaultEmailAddress, defaultEmailName);
                    //LiemBT modify: 28/12/2010
                    if (emailBO.EmailReplyToAddr != null && emailBO.EmailReplyToAddr.Trim().Length > 0)
                    {
                        mailMessage.ReplyTo = new MailAddress(emailBO.EmailReplyToAddr.Split(';')[0].ToString());
                    }
                    else
                    {
                        mailMessage.ReplyTo = new MailAddress(emailBO.EmailReplyToAddr);
                    }

                    //Subject & Body
                    mailMessage.Subject = emailBO.Subject;
                    mailMessage.Body = emailBO.MessageBody;
                    mailMessage.IsBodyHtml = emailBO.IsBodyHtml.Value;

                    #region ADD RECIPIENTS
                    foreach (EmailTransmissionRecipientBO emailTo in emailBO.EmailTransmissionRecipientBOList)
                    {
                        if (EmailUtils.IsValid(emailTo.RecipientEmailAddr))
                        {
                            MailAddress mailTo = new MailAddress(emailTo.RecipientEmailAddr, emailTo.RecipientEmailName);
                            switch (emailTo.RecipientType)
                            {
                                case EmailRecipientType.Cc:
                                    mailMessage.CC.Add(mailTo);
                                    break;

                                case EmailRecipientType.Bcc:
                                    mailMessage.Bcc.Add(mailTo);
                                    break;

                                case EmailRecipientType.To:
                                default:
                                    mailMessage.To.Add(mailTo);
                                    break;
                            }
                        }
                    }
                    #endregion

                    #region ADD ATTACHMENTS
                    foreach (EmailTransmissionAttachmentBO file in emailBO.EmailTransmissionAttachmentBOList)
                    {
                        //Get Files From FileScan System
                        if (file.DocID.HasValue)
                        {
                            //FileScanInfo fileInfo = FileScanUtils.GetDocument1(file.DocID.Value, false);
                            AttachmentInfoList list = AttachmentInfoList.GetAttachmentInfoListByDocID(file.DocID.Value);
                            string fileData = string.Empty;
                            if (list.Count > 0)
                            {
                                fileData = FileUtils.FileToBase64(FileScanUtils.GetFullFileName(list[0].FilePath));
                                if (file.DocID.Value > 0 && fileData !=null && fileData.Length > 0)
                                {
                                    file.Description = list[0].Description;

                                    Stream contentStream = new MemoryStream(Convert.FromBase64String(fileData));
                                    mailMessage.Attachments.Add(new Attachment(contentStream, list[0].FileName));
                                }
                            }
                        }
                    }
                    #endregion

                    smtpSend.Send(mailMessage);

                    emailBO.TransmissionCompleteFlag = true;
                    //issue 1326033
                    emailBO.IsSent = true;
                }
                catch (Exception ex)
                {
                    emailBO.Retry += 1;

                    if (emailBO.Retry.ToString() == ConfigurationManager.AppSettings["EMAIL_RETRY"])
                    {
                        emailBO.TransmissionCompleteFlag = true;
                    }
                    emailBO.DetailFailure += string.Format("[Retry-{0} : {1}]", emailBO.Retry, ex.Message);
                    //issue 1326033
                    emailBO.IsSent = false;
                }

                emailBO.ApplyEdit();
                emailBO.Save();
            }
        }
    }
}
